package cn.virens.common.spring.filter;

import cn.virens.common.util.exception.APIException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import org.dromara.hutool.core.text.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public abstract class AbstractPathMatcherFilter extends OncePerRequestFilter {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    protected final List<PathPatternItem> patterns = new ArrayList<>();
    protected final PathMatcher matcher = new AntPathMatcher();

    private String mWebApplicationContextName;

    /**
     * 添加需要放行的路径(如果为空全拦截)
     */
    public void addWhitePatterns(String pattern) throws APIException {
        this.patterns.add(PathPatternItem.white(matcher, pattern));
    }

    /**
     * 添加需要拦截的路径(如果为空全拦截)
     */
    public void addBlackPatterns(String pattern) throws APIException {
        this.patterns.add(PathPatternItem.black(matcher, pattern));
    }

    public String getWebApplicationContextName() {
        return mWebApplicationContextName;
    }

    public void setWebApplicationContextName(String mWebApplicationContextAttributeName) {
        this.mWebApplicationContextName = mWebApplicationContextAttributeName;
    }

    protected WebApplicationContext findWebApplicationContext() throws APIException {
        if (mWebApplicationContextName == null || mWebApplicationContextName.isEmpty()) {
            return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        } else {
            return WebApplicationContextUtils.getWebApplicationContext(getServletContext(), mWebApplicationContextName);
        }
    }

    protected <T> T getBean(String name, Class<T> requiredType) throws APIException {
        return findWebApplicationContext().getBean(name, requiredType);
    }

    protected <T> T getBean(Class<T> requiredType) throws APIException {
        return findWebApplicationContext().getBean(requiredType);
    }

    protected boolean match(HttpServletRequest request, String path) throws ServletException {
        return patterns_sorted().filter(item -> item.match(path))//
                .findFirst().filter(PathPatternItem::is_black)//
                .isEmpty();
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return match(request, request.getRequestURI());
    }

    protected static boolean isJsonRequest(HttpServletRequest request) throws APIException {
        if (!StrUtil.containsAnyIgnoreCase(request.getContentType(), "application/json")) {
            if (!StrUtil.endWithIgnoreCase(request.getRequestURI(), ".json")) {
                return CorsUtils.isCorsRequest(request);
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    /**
     * 返回排序后的路径匹配器
     */
    protected Stream<PathPatternItem> patterns_sorted() throws APIException {
        return patterns.stream().sorted(PathPatternItem::compare);
    }
}
